package com.netcracker.lab1.model;

import com.netcracker.lab1.utils.Generator;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: nocturne
 * Date: 10.01.13
 * Time: 11:57
 * To change this template use File | Settings | File Templates.
 */
class GenreManager extends AbstractGenreManager {

    private static HashMap<Integer, Genre> genreHashMap = new HashMap<Integer, Genre>();

    @Override
    public Genre createGenre(Integer id, String genreName) {
        Genre genre = new Genre(Generator.getInstance().next());
        genre.setGenreName(genreName);
        genre.setId(id);

        for (Map.Entry<Integer,Genre> entry: genreHashMap.entrySet()){
            if(!entry.getValue().getGenreName().equals(genreName)) {
                genreHashMap.put(genre.getId(), genre);
                return genre;
            }
        }

        throw new IllegalArgumentException("genre name " + genreName + " found");
    }

    @Override
    public Genre findGenreName(Integer id) {
        if (id >= 0 && id <= genreHashMap.size()) {
            return genreHashMap.get(id);
        }else {
            throw new IllegalArgumentException("not found genre by id = " + id);
        }
    }

    @Override
    public void deleteGenreById(Integer id) {
        if (id >= 0 && id <= genreHashMap.size()) {
            genreHashMap.remove(id);
        } else {
            throw new IllegalArgumentException("not found genre by id = " + id);
        }
    }

    @Override
    public void saveGenres(String path) throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        oos.writeObject(genreHashMap);
        oos.flush();
        oos.close();
    }

    @Override
    public void openGenres(String path) throws FileNotFoundException, IOException, ClassNotFoundException {
        genreHashMap = null;

        FileInputStream fis = new FileInputStream(path);
        ObjectInputStream oin = new ObjectInputStream(fis);
        genreHashMap = (HashMap) oin.readObject();
    }

    /*не уверен в правильности*/
    @Override
    public void editGenre(Integer id, String genreName) {
        createGenre(id, genreName);
    }

    @Override
    public int getSizeGenres() {
        return genreHashMap.size();
    }
}
